import React, { useState } from 'react';
import { Table, Tag, Tooltip, Button, Modal, message } from 'antd';
import { InfoCircleOutlined, FileTextOutlined, ApartmentOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { TablePaginationConfig } from 'antd/es/table/interface';
import CallGraphViewer from '../../CallGraphTab/CallGraphViewer';
import type { CallGraphData } from '../../CallGraphTab/types';
import { queryCallGraph } from '../../../../services/callGraphService';

interface ApiTableProps {
    data: any[];
    pagination: TablePaginationConfig;
    loading: boolean;
    onChange: (page: number, pageSize: number) => void;
    unitInfo?: any;
}

interface ApiRecord {
    unitId: string;
    className: string;
    packageName: string;
    methodName: string;
    methodSignature: string;
    inputParam: string;
    outputParam: string;
    filePath: string;
    startLine: number;
    endLine: number;
    totalLine: number;
    methodHash: string;
    isEntry: boolean;
    serviceName: string;
    serviceType: string;
    avgDailyCalls?: number;
    gitCreateTime?: string;
    gitLastEditTime?: string;
    gitLastEditEmp?: string;
    gitLastEditCommitId?: string;
    gitLastEditMsg?: string;
    noCodeChangeDurationDays?: number;
    saExists?: boolean;
    noSaCallDurationDays?: number;
    firstFoundTime?: string;
    lastInvocationTime?: string;
    saDataUpdateTime?: string;
    apmExists?: boolean;
    apmLast6mCount?: number;
    apmLast1yCount?: number;
    apmLast2yCount?: number;
    apmDataUpdateTime?: string;
    // SA累计运行时长（毫秒）
    saScannedUptimeMs?: number;
    // 废弃分析字段
    deprecationScore?: number;
    deprecationLevel?: string;
    deprecationReason?: string;
    deprecationUpdateTime?: string;
}

// 添加自定义样式
const customTooltipStyle = `
.ant-tooltip.custom-tooltip {
    max-width: 400px !important;
}
.ant-tooltip.custom-tooltip .ant-tooltip-content {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
}
.ant-tooltip.custom-tooltip .ant-tooltip-inner {
    background: #ffffff !important;
    border: none !important;
    outline: none !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
    border-radius: 8px !important;
    padding: 0 !important;
    color: #262626 !important;
    min-height: auto !important;
}
.ant-tooltip.custom-tooltip .ant-tooltip-arrow {
    display: none !important;
}
`;

// 注入样式
if (typeof document !== 'undefined') {
    const styleId = 'api-table-tooltip-style';
    if (!document.getElementById(styleId)) {
        const style = document.createElement('style');
        style.id = styleId;
        style.textContent = customTooltipStyle;
        document.head.appendChild(style);
    }
}

// 格式化时间的函数
const formatTime = (timeStr: string): string => {
    if (!timeStr) return '-';

    try {
        const date = new Date(timeStr);
        if (isNaN(date.getTime())) return timeStr;

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
        return timeStr;
    }
};

const ApiTable: React.FC<ApiTableProps> = ({ data, pagination, loading, onChange, unitInfo }) => {
    const [callGraphModalVisible, setCallGraphModalVisible] = useState(false);
    const [callGraphData, setCallGraphData] = useState<CallGraphData | null>(null);
    const [callGraphLoading, setCallGraphLoading] = useState(false);
    const [currentMethodClass, setCurrentMethodClass] = useState<string>('');
    const [currentMethodName, setCurrentMethodName] = useState<string>('');

    // 查看调用链路
    const handleViewCallGraph = async (record: ApiRecord) => {
        if (!unitInfo?.unitId) {
            message.error('单元ID不存在');
            return;
        }

        // 使用methodSignature作为查询目标
        const target = record.methodSignature || `${record.className}.${record.methodName}`;
        // 分别设置类名和方法名用于显示
        setCurrentMethodClass(record.className);
        setCurrentMethodName(record.methodName);
        setCallGraphModalVisible(true);
        setCallGraphLoading(true);

        try {
            const res: any = await queryCallGraph({
                unitId: unitInfo.unitId,
                target: target,
                queryType: 'METHOD',
                depth: 3,
                includeUpstream: true,
                includeDownstream: true
            });
            setCallGraphData(res?.data || res);
        } catch (e: any) {
            message.error(e?.message || '查询调用链路失败');
            setCallGraphData(null);
        } finally {
            setCallGraphLoading(false);
        }
    };

    // 获取调用频率标签
    const getFrequencyTag = (avgDailyCalls?: number) => {
        if (avgDailyCalls === undefined || avgDailyCalls === null || avgDailyCalls === 0) {
            return <Tag color="default">无调用记录</Tag>;
        } else if (avgDailyCalls >= 10) {
            return <Tag color="red">高频</Tag>;
        } else if (avgDailyCalls >= 1) {
            return <Tag color="orange">中频</Tag>;
        } else {
            return <Tag color="yellow">低频</Tag>;
        }
    };

    // 毫秒转为“X天X小时X分”（不足1天时省略天，不足1小时仅显示“X分”）
    const formatDuration = (ms?: number): string => {
        if (ms === undefined || ms === null || ms <= 0) return '-';
        const totalMinutes = Math.floor(ms / 60000);
        const days = Math.floor(totalMinutes / 1440);
        const remMinutesAfterDays = totalMinutes % 1440;
        const hours = Math.floor(remMinutesAfterDays / 60);
        const minutes = remMinutesAfterDays % 60;
        if (days > 0) return `${days}天${hours}小时${minutes}分`;
        if (hours > 0) return `${hours}小时${minutes}分`;
        return `${minutes}分`;
    };

    // 获取服务类型标签
    const getServiceTypeTag = (serviceType: string) => {
        const typeConfig = {
            'REST': { text: 'REST', color: 'blue', desc: 'REST接口方法' },
            'DUBBO': { text: 'DUBBO', color: 'green', desc: 'Dubbo接口方法' },
            'MAIN': { text: 'MAIN', color: 'orange', desc: 'main方法' },
            'NONE': { text: 'NONE', color: 'default', desc: '非入口方法' }
        };

        const config = typeConfig[serviceType as keyof typeof typeConfig] ||
            { text: serviceType || '未知', color: 'default', desc: '' };

        return <Tag color={config.color} title={config.desc}>{config.text}</Tag>;
    };

    const columns: ColumnsType<ApiRecord> = [
        {
            title: 'API名',
            dataIndex: 'serviceName',
            key: 'serviceName',
            width: 250,
            render: (text: string, record: ApiRecord) => {
                // 对于 DUBBO 接口，将方法名附加到服务名后面
                const displayName = record.serviceType === 'DUBBO' && text && record.methodName
                    ? `${text}#${record.methodName}`
                    : text;

                return (
                    <Tooltip title={displayName}>
                        <div style={{
                            width: '100%',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            fontWeight: 'bold',
                            color: '#1890ff',
                            padding: '0',
                            margin: '0'
                        }}>
                            {displayName}
                        </div>
                    </Tooltip>
                );
            },
        },
        {
            title: 'API类型',
            dataIndex: 'serviceType',
            key: 'serviceType',
            width: 100,
            render: (serviceType: string) => getServiceTypeTag(serviceType),
        },
        {
            title: '类名+方法名',
            dataIndex: 'methodName',
            key: 'classMethod',
            width: 200,
            render: (methodName: string, record: ApiRecord) => (
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <div style={{
                        width: '100%',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        padding: '0',
                        margin: '0'
                    }}>
                        <span style={{ color: '#666', fontSize: '12px' }}>{record.className}.</span>
                        <span style={{ fontWeight: 'bold' }}>{methodName}</span>
                    </div>
                    <Tooltip
                        title={
                            <div style={{
                                width: '380px',
                                textAlign: 'left',
                                backgroundColor: '#ffffff',
                                padding: '16px',
                                borderRadius: '8px',
                                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
                                border: '1px solid #f0f0f0'
                            }}>
                                <div style={{
                                    fontSize: '16px',
                                    fontWeight: '600',
                                    marginBottom: '16px',
                                    color: '#1890ff',
                                    borderBottom: '1px solid #f0f0f0',
                                    paddingBottom: '8px',
                                    display: 'flex',
                                    alignItems: 'center'
                                }}>
                                    <FileTextOutlined style={{ marginRight: '8px', fontSize: '16px' }} />
                                    方法详情
                                </div>

                                <div style={{ marginBottom: '12px' }}>
                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>包名</div>
                                    <div style={{ fontSize: '13px', color: '#262626', marginBottom: '8px' }}>
                                        {record.packageName}
                                    </div>

                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>完整类名</div>
                                    <div style={{ fontSize: '13px', color: '#262626', marginBottom: '8px' }}>
                                        {record.packageName}.{record.className}
                                    </div>

                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>方法签名</div>
                                    <div style={{
                                        fontFamily: 'monospace',
                                        fontSize: '11px',
                                        color: '#262626',
                                        backgroundColor: '#f5f5f5',
                                        padding: '6px 8px',
                                        borderRadius: '4px',
                                        border: '1px solid #e8e8e8',
                                        wordBreak: 'break-all',
                                        marginBottom: '8px'
                                    }}>
                                        {record.methodSignature || '-'}
                                    </div>

                                    <div style={{ display: 'flex', gap: '16px', marginBottom: '8px' }}>
                                        <div style={{ flex: 1 }}>
                                            <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>输入参数</div>
                                            <div style={{ fontSize: '12px', color: '#262626' }}>
                                                {record.inputParam || '-'}
                                            </div>
                                        </div>
                                        <div style={{ flex: 1 }}>
                                            <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>输出参数</div>
                                            <div style={{ fontSize: '12px', color: '#262626' }}>
                                                {record.outputParam || '-'}
                                            </div>
                                        </div>
                                    </div>

                                    <div style={{ display: 'flex', gap: '16px' }}>
                                        <div style={{ flex: 1 }}>
                                            <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>文件路径</div>
                                            <div style={{ fontSize: '12px', color: '#666', wordBreak: 'break-all' }}>
                                                {record.filePath}
                                                {record.startLine && (
                                                    <span style={{ color: '#1890ff' }}> :{record.startLine}-{record.endLine}</span>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        }
                        placement="right"
                        overlayStyle={{ maxWidth: '400px' }}
                        overlayClassName="custom-tooltip"
                    >
                        <InfoCircleOutlined
                            style={{
                                color: '#1890ff',
                                cursor: 'pointer',
                                fontSize: '14px'
                            }}
                        />
                    </Tooltip>
                </div>
            ),
        },
        {
            title: '调用频次',
            dataIndex: 'avgDailyCalls',
            key: 'avgDailyCalls',
            width: 120,
            render: (avgDailyCalls: number) => (
                <div>
                    {getFrequencyTag(avgDailyCalls)}
                    {avgDailyCalls && avgDailyCalls > 0 && (
                        <div style={{ fontSize: '11px', color: '#999', marginTop: '2px' }}>
                            {avgDailyCalls.toFixed(2)} 次/天
                        </div>
                    )}
                </div>
            ),
        },
        {
            title: '变更历史',
            dataIndex: 'noCodeChangeDurationDays',
            key: 'noCodeChangeDurationDays',
            width: 120,
            render: (days: number, record: ApiRecord) => {
                const displayDays = days !== undefined && days !== null ? `${days}天` : '-';

                // 构建详细信息tooltip
                const tooltipContent = (
                    <div style={{
                        width: '280px',
                        textAlign: 'left',
                        backgroundColor: '#ffffff',
                        padding: '16px',
                        borderRadius: '8px',
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                        border: '1px solid #f0f0f0'
                    }}>
                        <div style={{
                            fontSize: '14px',
                            fontWeight: '600',
                            marginBottom: '12px',
                            color: '#1890ff',
                            borderBottom: '1px solid #f0f0f0',
                            paddingBottom: '6px'
                        }}>
                            📝 最近修改详情
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '60px' }}>修改人：</span>
                                <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                    {record.gitLastEditEmp || '-'}
                                </span>
                            </div>
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '60px' }}>修改时间：</span>
                                <span style={{ fontSize: '12px', color: '#262626' }}>
                                    {formatTime(record.gitLastEditTime || '')}
                                </span>
                            </div>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '60px' }}>提交ID：</span>
                                <span style={{
                                    fontSize: '12px',
                                    color: '#262626',
                                    fontFamily: 'monospace',
                                    padding: '2px 6px',
                                    backgroundColor: '#f5f5f5',
                                    borderRadius: '4px'
                                }}>
                                    {record.gitLastEditCommitId ? record.gitLastEditCommitId.substring(0, 8) : '-'}
                                </span>
                            </div>
                            <div>
                                <div style={{ color: '#8c8c8c', fontSize: '12px', marginBottom: '4px' }}>提交信息：</div>
                                <div style={{
                                    fontSize: '12px',
                                    color: '#262626',
                                    backgroundColor: '#f9f9f9',
                                    padding: '8px',
                                    borderRadius: '4px',
                                    border: '1px solid #f0f0f0',
                                    wordBreak: 'break-word',
                                    lineHeight: '1.4'
                                }}>
                                    {record.gitLastEditMsg || '-'}
                                </div>
                            </div>
                        </div>
                    </div>
                );

                return (
                    <Tooltip
                        title={tooltipContent}
                        placement="topLeft"
                        overlayClassName="custom-tooltip"
                    >
                        <span style={{ cursor: 'pointer', borderBottom: '1px dashed #1890ff' }}>
                            {displayDays}
                        </span>
                    </Tooltip>
                );
            }
        },
        {
            title: 'APM状态',
            dataIndex: 'apmExists',
            key: 'apmExists',
            width: 100,
            render: (apmExists: boolean | null, record: ApiRecord) => {
                const tooltipContent = (
                    <div style={{
                        width: '280px',
                        textAlign: 'left',
                        backgroundColor: '#ffffff',
                        padding: '16px',
                        borderRadius: '8px',
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                        border: '1px solid #f0f0f0'
                    }}>
                        <div style={{
                            fontSize: '14px',
                            fontWeight: '600',
                            marginBottom: '12px',
                            color: '#1890ff',
                            borderBottom: '1px solid #f0f0f0',
                            paddingBottom: '6px'
                        }}>
                            📈 APM调用详情
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>APM状态：</span>
                                <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                    {apmExists === true ? '已发现' : '未发现'}
                                </span>
                            </div>
                            {apmExists === true && (
                                <>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>6个月调用：</span>
                                        <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                            {record.apmLast6mCount !== null && record.apmLast6mCount !== undefined ? record.apmLast6mCount.toLocaleString() : '0'}
                                        </span>
                                    </div>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>1年调用：</span>
                                        <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                            {record.apmLast1yCount !== null && record.apmLast1yCount !== undefined ? record.apmLast1yCount.toLocaleString() : '0'}
                                        </span>
                                    </div>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>平均调用：</span>
                                        <span style={{ fontSize: '12px', color: '#262626' }}>
                                            {record.avgDailyCalls && record.avgDailyCalls > 0 ? `${record.avgDailyCalls.toFixed(2)} 次/天` : '-'}
                                        </span>
                                    </div>
                                </>
                            )}
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>数据更新：</span>
                                <span style={{ fontSize: '12px', color: '#262626' }}>
                                    {record.apmDataUpdateTime || '-'}
                                </span>
                            </div>
                        </div>
                    </div>
                );

                const getStatusDisplay = () => {
                    if (apmExists === true) {
                        return <Tag color="green">已发现</Tag>;
                    } else {
                        return <Tag color="red">未发现</Tag>;
                    }
                };

                return (
                    <Tooltip
                        title={tooltipContent}
                        placement="topLeft"
                        overlayClassName="custom-tooltip"
                    >
                        <span style={{ cursor: 'pointer' }}>
                            {getStatusDisplay()}
                        </span>
                    </Tooltip>
                );
            }
        },
        {
            title: 'SA状态',
            dataIndex: 'saExists',
            key: 'saExists',
            width: 100,
            render: (saExists: boolean | null, record: ApiRecord) => {
                // SA状态判断：只有saExists为true且累计扫描时长大于0且有最后调用时间才算"已发现"
                const isReallyFound = saExists === true && record.saScannedUptimeMs && record.saScannedUptimeMs > 0 && record.lastInvocationTime;

                const tooltipContent = (
                    <div style={{
                        width: '280px',
                        textAlign: 'left',
                        backgroundColor: '#ffffff',
                        padding: '16px',
                        borderRadius: '8px',
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                        border: '1px solid #f0f0f0'
                    }}>
                        <div style={{
                            fontSize: '14px',
                            fontWeight: '600',
                            marginBottom: '12px',
                            color: '#fa8c16',
                            borderBottom: '1px solid #f0f0f0',
                            paddingBottom: '6px'
                        }}>
                            📊 SA调用详情
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>SA状态：</span>
                                <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                    {isReallyFound ? '已发现' : '未发现'}
                                </span>
                            </div>
                            {isReallyFound && (
                                <>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>首次发现：</span>
                                        <span style={{ fontSize: '12px', color: '#262626' }}>
                                            {record.firstFoundTime || '-'}
                                        </span>
                                    </div>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>最后调用：</span>
                                        <span style={{ fontSize: '12px', color: '#262626' }}>
                                            {record.lastInvocationTime || '-'}
                                        </span>
                                    </div>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>无调用时长：</span>
                                        <span style={{ fontSize: '12px', color: '#262626' }}>
                                            {record.noSaCallDurationDays !== undefined && record.noSaCallDurationDays !== null ? `${record.noSaCallDurationDays}天` : '-'}
                                        </span>
                                    </div>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>累计扫描时长：</span>
                                        <span style={{ fontSize: '12px', color: '#262626' }}>
                                            {formatDuration(record.saScannedUptimeMs)}
                                        </span>
                                    </div>
                                </>
                            )}
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>数据更新：</span>
                                <span style={{ fontSize: '12px', color: '#262626' }}>
                                    {record.saDataUpdateTime || '-'}
                                </span>
                            </div>
                        </div>
                    </div>
                );

                const getStatusDisplay = () => {
                    if (isReallyFound) {
                        return <Tag color="green">已发现</Tag>;
                    } else {
                        return <Tag color="red">未发现</Tag>;
                    }
                };

                return (
                    <Tooltip
                        title={tooltipContent}
                        placement="topLeft"
                        overlayClassName="custom-tooltip"
                    >
                        <span style={{ cursor: 'pointer' }}>
                            {getStatusDisplay()}
                        </span>
                    </Tooltip>
                );
            }
        },
        {
            title: '废弃分析',
            dataIndex: 'deprecationLevel',
            key: 'deprecationLevel',
            width: 120,
            render: (level: string, record: ApiRecord) => {
                const getLevelConfig = (level: string) => {
                    const configs: { [key: string]: { text: string; color: string; bgColor: string } } = {
                        'EXTREME_RISK': { text: '极高风险', color: '#fff', bgColor: '#cf1322' },
                        'HIGH_RISK': { text: '高风险', color: '#fff', bgColor: '#ff4d4f' },
                        'MEDIUM_RISK': { text: '中风险', color: '#fff', bgColor: '#fa8c16' },
                        'LOW_RISK': { text: '低风险', color: '#fff', bgColor: '#fadb14' },
                        'MINIMAL_RISK': { text: '极低风险', color: '#fff', bgColor: '#52c41a' },
                    };
                    return configs[level] || { text: '未评估', color: '#666', bgColor: '#f0f0f0' };
                };

                const config = getLevelConfig(level);
                const score = record.deprecationScore;

                const tooltipContent = (
                    <div style={{
                        width: '300px',
                        textAlign: 'left',
                        backgroundColor: '#ffffff',
                        padding: '16px',
                        borderRadius: '8px',
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                        border: '1px solid #f0f0f0'
                    }}>
                        <div style={{
                            fontSize: '14px',
                            fontWeight: '600',
                            marginBottom: '12px',
                            color: '#722ed1',
                            borderBottom: '1px solid #f0f0f0',
                            paddingBottom: '6px'
                        }}>
                            🔍 废弃分析详情
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>风险等级：</span>
                                <span style={{
                                    fontSize: '12px',
                                    fontWeight: '600',
                                    color: config.color,
                                    backgroundColor: config.bgColor,
                                    padding: '2px 8px',
                                    borderRadius: '4px'
                                }}>
                                    {config.text}
                                </span>
                            </div>
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>废弃分数：</span>
                                <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                    {score !== null && score !== undefined ? `${score.toFixed(1)} 分` : '-'}
                                </span>
                            </div>
                            {record.deprecationReason && (
                                <div>
                                    <div style={{ color: '#8c8c8c', fontSize: '12px', marginBottom: '4px' }}>废弃原因：</div>
                                    <div style={{
                                        fontSize: '12px',
                                        color: '#262626',
                                        backgroundColor: '#f9f9f9',
                                        padding: '8px',
                                        borderRadius: '4px',
                                        border: '1px solid #f0f0f0',
                                        wordBreak: 'break-word',
                                        lineHeight: '1.4'
                                    }}>
                                        {record.deprecationReason}
                                    </div>
                                </div>
                            )}
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>分析时间：</span>
                                <span style={{ fontSize: '12px', color: '#262626' }}>
                                    {record.deprecationUpdateTime || '-'}
                                </span>
                            </div>
                        </div>
                    </div>
                );

                return (
                    <Tooltip
                        title={tooltipContent}
                        placement="topLeft"
                        overlayClassName="custom-tooltip"
                    >
                        <div style={{ cursor: 'pointer' }}>
                            <div style={{
                                display: 'inline-block',
                                padding: '2px 8px',
                                borderRadius: '4px',
                                fontSize: '12px',
                                fontWeight: '500',
                                color: config.color,
                                backgroundColor: config.bgColor
                            }}>
                                {config.text}
                            </div>
                            {score !== null && score !== undefined && (
                                <div style={{ fontSize: '11px', color: '#999', marginTop: '2px' }}>
                                    {score.toFixed(1)} 分
                                </div>
                            )}
                        </div>
                    </Tooltip>
                );
            }
        },
        {
            title: '操作',
            key: 'action',
            width: 100,
            fixed: 'right',
            render: (_: any, record: ApiRecord) => (
                <Button
                    type="link"
                    size="small"
                    icon={<ApartmentOutlined />}
                    onClick={() => handleViewCallGraph(record)}
                >
                    查看链路
                </Button>
            ),
        },
    ];

    return (
        <div>
            <Table
                columns={columns}
                dataSource={data}
                rowKey="methodSignature"
                loading={loading}
                pagination={{
                    ...pagination,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total, range) =>
                        `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
                    onChange: (page, pageSize) => onChange(page, pageSize || 10),
                    onShowSizeChange: (current, size) => onChange(current, size),
                }}
                scroll={{ x: 1300 }}
                size="small"
                bordered
                style={{
                    backgroundColor: '#fff',
                    borderRadius: '8px',
                    overflow: 'visible',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                }}
            />

            <Modal
                title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <ApartmentOutlined style={{ color: '#1890ff' }} />
                        <span>方法调用链路</span>
                    </div>
                }
                open={callGraphModalVisible}
                onCancel={() => {
                    setCallGraphModalVisible(false);
                    setCallGraphData(null);
                    setCurrentMethodClass('');
                    setCurrentMethodName('');
                }}
                footer={null}
                width="90%"
                style={{ top: 20 }}
                styles={{ body: { height: 'calc(100vh - 200px)', overflow: 'auto' } }}
            >
                <div style={{ marginBottom: 16, padding: '12px 16px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                    <div style={{ marginBottom: 8 }}>
                        <span style={{ color: '#666', fontSize: '12px', marginRight: '8px' }}>目标类：</span>
                        <span style={{ fontFamily: 'monospace', fontSize: '13px', color: '#1890ff', fontWeight: '500' }}>
                            {currentMethodClass}
                        </span>
                    </div>
                    <div>
                        <span style={{ color: '#666', fontSize: '12px', marginRight: '8px' }}>目标方法：</span>
                        <span style={{ fontFamily: 'monospace', fontSize: '13px', color: '#262626', fontWeight: '600' }}>
                            {currentMethodName}
                        </span>
                    </div>
                </div>
                {callGraphData ? (
                    <CallGraphViewer data={callGraphData} loading={callGraphLoading} />
                ) : (
                    <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
                        {callGraphLoading ? '加载中...' : '暂无调用链路数据'}
                    </div>
                )}
            </Modal>
        </div>
    );
};

export default ApiTable;
